/**
 * @file add_custom.cpp
 *
 * Copyright (C) 2024. Huawei Technologies Co., Ltd. All rights reserved.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
#include "kernel_operator.h"

constexpr int32_t TOTAL_LENGTH = 8 * 2048;                            // total length of data
constexpr int32_t USE_CORE_NUM = 8;                                   // num of core used
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;         // length computed of each core
constexpr int32_t TILE_NUM = 8;                                       // split data into 8 tiles for each core
constexpr int32_t BUFFER_NUM = 2;                                     // tensor num for each queue
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM; // separate to 2 parts, due to double buffer

class KernelLeakyreluGrad {
public:
    __aicore__ inline KernelLeakyreluGrad() {}
    __aicore__ inline void Init(GM_ADDR dy, GM_ADDR x, GM_ADDR dx, float negativeSlope)
    {
        this->negativeSlope = static_cast<float>(negativeSlope);

        dyGm.SetGlobalBuffer((__gm__ float *)dy + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        xGm.SetGlobalBuffer((__gm__ float *)x + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        dxGm.SetGlobalBuffer((__gm__ float *)dx + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);

        pipe.InitBuffer(inQueueDy, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(inQueueX, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(tmpBuffer, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(outQueueDx, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(tmp1Buffer, TILE_LENGTH * sizeof(float));     
        

    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = TILE_NUM * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> dyLocal = inQueueDy.AllocTensor<float>();
        AscendC::DataCopy(dyLocal, dyGm[progress * TILE_LENGTH], TILE_LENGTH);
        inQueueDy.EnQue(dyLocal);
        
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        AscendC::DataCopy(xLocal, xGm[progress * TILE_LENGTH], TILE_LENGTH);
        inQueueX.EnQue(xLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> dyLocal = inQueueDy.DeQue<float>();
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<float> dxLocal = outQueueDx.AllocTensor<float>();
        AscendC::LocalTensor<uint8_t> mask = tmpBuffer.Get<uint8_t>();
        AscendC::LocalTensor<float> negativePart = tmp1Buffer.Get<float>();

        // 计算LeakyReLU梯度: dx = dy * (x > 0 ? 1.0 : negativeSlope)
        // 1. 创建掩码：x > 0
        AscendC::CompareScalar(mask, xLocal, 0.0f, AscendC::CMPMODE::GT, TILE_LENGTH);
        AscendC::DataCopy(negativePart, dyLocal, TILE_LENGTH);
        AscendC::Muls(negativePart, negativePart, this->negativeSlope, TILE_LENGTH);
        AscendC::Select(dxLocal, mask, dyLocal, negativePart, AscendC::SELMODE::VSEL_TENSOR_TENSOR_MODE, TILE_LENGTH);
        
        // 将结果放入输出队列
        outQueueDx.EnQue<float>(dxLocal);
        
        // 释放输入队列中的张量
        inQueueDy.FreeTensor(dyLocal);
        inQueueX.FreeTensor(xLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> dxLocal = outQueueDx.DeQue<float>();
        AscendC::DataCopy(dxGm[progress * TILE_LENGTH], dxLocal, TILE_LENGTH);
        outQueueDx.FreeTensor(dxLocal);
    }

private:
  	float negativeSlope;

    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueDy;  // 上游梯度队列
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;   // 前向输入队列
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueDx; // 梯度输出队列
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuffer;            // 临时计算缓冲区
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmp1Buffer;

    AscendC::GlobalTensor<float> dyGm;  // 上游梯度全局张量
    AscendC::GlobalTensor<float> xGm;   // 前向输入全局张量
    AscendC::GlobalTensor<float> dxGm; 
};

extern "C" __global__ __aicore__ void leakyrelugrad_custom(GM_ADDR dy, GM_ADDR x, GM_ADDR dx, float negativeSlope)
{
    KernelLeakyreluGrad op;
    op.Init(dy, x, dx, negativeSlope);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void leakyrelugrad_custom_do(uint32_t blockDim, void *stream, uint8_t *dy, uint8_t *x, uint8_t *dx, float negativeSlope)
{
    leakyrelugrad_custom<<<blockDim, nullptr, stream>>>(dy, x, dx, negativeSlope);
}
#endif
